var mapToolsWin;
var mapToolBtn;
var measureControls;
var control = '';

// TODO: try implement DIV creation on the fly
initMapToolsDiv = function() {
	var maptools = {
		xtype : 'panel',
		width : '100%',
		height : 600,
		itemId : 'tool1',
		align : 'center',
		border : false,
		bodyStyle : 'padding:0px 0px 0px 20px;align:center;font: normal 10px Verdana, Times New Roman, Times, serif;color:white;',
		html : '<div id="container_contant_area">'
				+ '<a href="#" class="top_link" onclick="createSearchWindow()">'
				+ '<div id="top_tab">'
				+ '<div id="maptool_tab"><img id="mapToolBtn" src="images/map/nis_top_tabs_15.png"/></div>'
				+ '</div>' + '</a>' + '</div>',
		listeners : {
			click : function() {
				alert('on tool button 1...');
			}
		}
	};
};

initToolsWindow = function( _id, _target, _title, _htmlContent, _contentEl, _height, _width ){
	new Ext.Window( {
		layout : 'fit',
		width : _width ? _width :  Ext.getCmp( _target ).getWidth(),
		height : _height,
		id: _id,
		animateTarget : _target,
		html : _htmlContent,
		contentEl : _contentEl,
		draggable: false,
		plain:true,
		border:true,
		resizable:false,
		shadow:false,
		frame:true,
		title : _title,
		closeAction : 'hide',
		listeners : {
			'hide' : function() {
				this.hide();
			},
			'beforehide' : function(){
				Ext.getCmp(_target).show();
			},
			'beforeshow' : function(){
				Ext.get(_id).show();
			}
		}
	}).hide();
};

mapLegendDivContent = function() {
	var htmlOut = '<div class="legend"/>'+
	'<div class="legendRow">'+
	'<div class="legendBox earth"></div>'+
	'<div class="legDesc">'+worldmapLabel+'</div>'+
	'</div>'+
	'<div class="legendRow">'+
	'<div class="legendBox sea"></div>'+
	'<div class="legDesc">'+seaLabel+'</div>'+
	'</div>'+
	'<div class="legendRow">'+
	'<div class="legendBox region"></div>'+
	'<div class="legDesc">'+regionLabel+'</div>'+
	'</div>'+
	'<div class="legendRow">'+
	'<div class="legendPoint department"></div>'+
	'<div class="legDesc">'+departmentLabel+'</div>'+
	'</div>'+
	'<div class="legendRow">'+
	'<div class="legendPoint city"></div>'+
	'<div class="legDesc">'+citybranchLabel+'</div>'+
	'</div>'+
	/*'<div class="legendRow">'+
	'<div class="legendBox others"></div>'+
	'<div class="legDesc">'+otherLabel+'</div>'+
	'</div>'+-->*/
	'</div>';
	return htmlOut;
};
metaDateDivContent = function() {
	var htmlOut = ' &#169; 2010 all rights reserved';
	return htmlOut;
};

initMapToolsWin = function() {
	Ext.QuickTips.init();

	// initMapToolsDiv();
	Ext.get('mapTool').show();

	mapToolsWin = new Ext.Window( {
		width : 362,
		height : 37,
		draggable : false,
		plain : true,
		layout : 'menu',
		id : 'mapToolsWin',
		contentEl : 'mapTool',
		baseCls : 'mapTool1',
		border : false,
		resizable : false,
		shadow : false,
		frame : false,
		animateTarget : 'mapMenu',
		closable : false/*,
		items : [ {
			xtype : 'panel',
			baseCls : 'mapTool',
			style : 'padding:3px 0 0 10px',
			border : false
		} ]*/
	});
	if((Ext.isIE) && (languageName=='arabic'))
	{
		mapToolsWin.setPosition(400, 120);
	}
	else{
	mapToolsWin.setPosition(0, 120);
	}
};

showMapToolWin = function() { // @ js/helper/menu.js
	mapToolBtn = Ext.get('mapMenu');
	if (!mapToolsWin.isVisible()) {
		mapToolBtn.setVisible(false);
		mapToolsWin.show();
	} else {
		mapToolsWin.setVisible(false);
	}
};

initMeasureTool = function() {

	initMeasureWindow(); // @ js/mapjs/mapTools.js#initMeasureWindow

	// For measure
	sketchSymbolizers = {
		"Point" : {
			pointRadius : 4,
			graphicName : "square",
			fillColor : "white",
			fillOpacity : 1,
			strokeWidth : 1,
			strokeOpacity : 1,
			strokeColor : "#333333"
		},
		"Line" : {
			strokeWidth : 3,
			strokeOpacity : 1,
			strokeColor : "#666666",
			strokeDashstyle : "solid"
		},
		"Polygon" : {
			strokeWidth : 2,
			strokeOpacity : 1,
			strokeColor : "#666666",
			fillColor : "white",
			fillOpacity : 0.3
		}
	};
	style = new OpenLayers.Style();
	style.addRules( [ new OpenLayers.Rule( {
		symbolizer : sketchSymbolizers
	}) ]);
	styleMap = new OpenLayers.StyleMap( {
		"default" : style
	});
};

initMeasureWindow = function() {

	/*
	 * var measureDiv = { xtype : 'panel', itemId : 'measurePanel', align :
	 * 'center', border : false, html : '<div id="measure"></div>', renderTo:
	 * Ext.getBody() };
	 */

	var MeasureWin = new Ext.Window( {
		width : 132,
		height : 20,
		draggable : false,
		plain : true,
		layout : 'fit',
		id : 'measureWin',
		contentEl : 'measure',
		cls : 'measure',
		border : true,
		resizable : false,
		shadow : false,
		frame : false,
		closeAction : 'hide',
		closable : false
	});
};

setToolbarContent = function(map) {

	toolbar.addControl(new OpenLayers.Control.ZoomToMaxExtent( {
		map : map,
		title : zoomMaxTitle
	}), {
		iconCls : 'maptool_fullwin',
		toggleGroup : 'map'
	});

	toolbar.addControl(new OpenLayers.Control.ZoomBox( {
		title : zoomInTitle
	}), {
		iconCls : 'maptool_zoomin',
		toggleGroup : 'map'
	});

	toolbar.addControl(new OpenLayers.Control.ZoomBox( {
		out : true,
			
		title : zoomOutTitle
	}), {
		iconCls : 'maptool_zoomout',
		toggleGroup : 'map'
	});

	toolbar.addControl(new OpenLayers.Control.DragPan( {
		isDefault : true,
		title : panMapTitle
	}), {
		iconCls : 'maptool_pan',
		toggleGroup : 'map'
	});

	nav = new OpenLayers.Control.NavigationHistory();
	map.addControl(nav);
	nav.activate();

	var buttonPrevious = new Ext.Toolbar.Button( {
		iconCls : 'maptool_back',
		tooltip : previousViewToolTip,
		disabled : false,
		handler : nav.previous.trigger
	});

	var buttonNext = new Ext.Toolbar.Button( {
		iconCls : 'maptool_forward',
		tooltip : nextViewToolTip,
		disabled : false,
		handler : nav.next.trigger
	});

	toolbar.add(buttonPrevious);
	toolbar.add(buttonNext);

	nav.previous.events.register("activate", buttonPrevious, function() {
		this.setDisabled(false);
	});

	nav.previous.events.register("deactivate", buttonPrevious, function() {
		this.setDisabled(true);
	});

	nav.next.events.register("activate", buttonNext, function() {
		this.setDisabled(false);
	});

	nav.next.events.register("deactivate", buttonNext, function() {
		this.setDisabled(true);
	});

	toolbar.addControl(new OpenLayers.Control.WMSGetFeatureInfo( {
		url : geoServer,
		title : informationTitleToolTip,
		queryVisible : true,
		eventListeners : {
			getfeatureinfo : function(event) {
				if (popup != "") {
					mapObj.removePopup(popup);
					popup.destroy();
					popup = "";
				}

				popup = new OpenLayers.Popup.FramedCloud("FeatureInfo", mapObj
						.getLonLatFromPixel(event.xy), null, event.text, null,
						true);
				mapObj.addPopup(popup);
			}
		}
	}), {
		iconCls : 'maptool_info',
		toggleGroup : 'map'
	});

	initMeasureTool(); // @ js/mapjs/mapTools.js#initMeasureTool
	toolbar
			.addControl(
					new OpenLayers.Control.Measure(
							OpenLayers.Handler.Path,
							{
								title : measureTitle,
								div : $('measure'),
								persist : true,
								
								eventListeners : {
									measure : function(evt) {
									var units = evt.units;
									var order = evt.order;
									var measure = evt.measure;
									var measureBtn = Ext.getCmp('measureWin');
									var mapCmp = Ext.getCmp('centerPanel');
									 var geometry = evt.geometry;
									var mapWidth = mapCmp.getInnerWidth();
									var mapHeight = mapCmp.getInnerHeight();
									var mapXPosition = (mapWidth-690);
									var mapYPosition = (mapHeight + 106);
									measureBtn.setPosition( locale == 'ar' ? mapWidth : mapXPosition, mapYPosition);
									measureBtn.show();

									var element = document.getElementById('measure');
									var out = "";
									if (order == 1) {
										out += (locale == 'ar' ? "\u0642\u064a\u0627\u0633 : "
												: "measure: ")
												+calcVincenty(geometry).toFixed(3)
												+ " "
												+ units;
									} else {
										out += "measure: "
											+ calcVincenty(geometry).toFixed(3) + " "
											+ units + "<sup>2</"
											+ "sup>";
									}
									element.innerHTML = out;
								}
								}
							}), {
						iconCls : 'maptool_measure',
						toggleGroup : 'map'
					});

	var btn9 = {
		xtype : 'tbbutton',
		iconCls : 'maptool_clear',
		tooltip : clearSearchToolTip,
		toggleGroup : 'map',
		listeners : {
			click : function(c) {
				clearAll();
				doAddCheckBoxComp();
				/* if (control) {
					mapObj.removeControl(control);
					control.destroy();
					control = '';
				} */
			}
		}
	};
	toolbar.add(btn9);

	var btn10 = {
		iconCls : 'maptool_min',
		tooltip : minimizeMapToolTip,
		xtype : 'tbbutton',
		handler : function() {
			mapToolsWin.hide();
			var mapToolBtn = Ext.get('mapMenu');
			mapToolBtn.show();
		}
	};
	toolbar.add(btn10);

};

toggleControlMeasure = function(element) {
    for(key in measureControls) {
    	control = measureControls[key];
        if(element.value == key && element.checked) {
        	control.activate();
        } else {
        	control.deactivate();
        }
    }
};
toggleGeodesic = function (element) {
    for(key in measureControls) {
    	control = measureControls[key];
    	control.geodesic = element.checked;
    }
};

createToolbar = function(map) {
	return new mapfish.widgets.toolbar.Toolbar( {
		map : map,
		configurable : false,
		border : true,
		baseCls : 'mapTool'
	});
	toolbar.autoHeight = false;
	toolbar.height = 29;
};

initSlider = function(mapObj) {
	mapObj.addControl(new OpenLayers.Control.Navigation());
	var slider = new GeoExt.ZoomSlider( {
		map : mapObj,
		aggressive : true,
		vertical : true,
		height : 212,
		plugins : new GeoExt.ZoomSliderTip( {
			template : "<div>Zoom Level: {zoom}</div>"
		}),
		renderTo : 'vertical-slider'
	});
};


initMapTools = function( mapObj ){
	initMapToolsWin(); // @ js/mapjs/mapTools.js
	toolbar = createToolbar(mapObj); // @ js/mapjs/mapTools.js
	setToolbarContent(mapObj);
	toolbar.activate();
	mapToolsWin.add(toolbar);
};

initMapPan = function ( mapObj ){
	mapObj.addControl( new OpenLayers.Control.PanZoomBar({ div : OpenLayers.Util.getElement("mappanzoombar")}) );

	Ext.getCmp('mappanzoombar').setPosition(Ext.getCmp('centerPanel').getInnerWidth()-50,  150);
	Ext.getCmp('mappanzoombar').show();
};

initMapScale = function ( mapObj ){
	

mapObj.addControl( new OpenLayers.Control.ScaleLine({div:OpenLayers.Util.getElement("mapscalebar")} ));

	Ext.getCmp('mapscalebar').setPosition( 5, Ext.getCmp('centerPanel').getInnerHeight() + 50 );
	Ext.getCmp('mapscalebar').show();
};

initMousePosition = function ( mapObj ){
	mapObj.addControl(new OpenLayers.Control.MousePosition( {id: "mousePoint"} ));
	var coordinateMenu = Ext.getDom('coordinateMenu'); var mousePoint = Ext.getDom('mousePoint');
	mapObj.events.register( "mousemove", mapObj, function(e) {
		coordinateMenu.className = 'x-menu x-menu-floating x-layer coordinateMousePoint';
		coordinateMenu.textContent = mousePoint.textContent;
		coordinateMenu.innerText = mousePoint.innerText;
    });
};
var layerSwitcher ;
initMapLayerSwitch = function ( mapObj ){
	layerSwitcher = new OpenLayers.Control.LayerSwitcher( { div:Ext.get('layersDiv'), roundedCorner : false } );
	mapObj.addControl( layerSwitcher );
	layerSwitcher.showControls( false );

	mapObj.events.register("changelayer", mapObj, function (e) {//on layer change
		$('input, select').uniform(); //reset to uniform
    });
};

initAllMapTools = function(mapObj) {
	//mapTools
	initMapTools		( mapObj );
	//other mapTools
	//initMapPan 			( mapObj ); //TODO: un-comment to show Pan
	//initSlider			( mapObj );
	initMapScale 		( mapObj );
	initMousePosition	( mapObj );
	initMapLayerSwitch	( mapObj );
	initMapOverView 	( mapObj ); //@ js/mapjs/mapOverView.js
	initToolsWindow( 'mapLegend', 'legendMenu', legendLabel, mapLegendDivContent(), '' , 200 );
	initToolsWindow( 'mapLayers', 'layersMenu', layersLabel, '', 'layersDiv', 200 );
	initToolsWindow( 'mapMetaData', 'metadataMenu', metadataLabel, metaDateDivContent(), '', 60, 375 );
	
	
};

function calcVincenty(geometry) {
    var dist = 0;
    for (var i = 1; i < geometry.components.length; i++) {
        var first = geometry.components[i-1];
        var second = geometry.components[i];
        dist += OpenLayers.Util.distVincenty(
            {lon: first.x, lat: first.y},
            {lon: second.x, lat: second.y}
        );
    }
    return dist;
}    
